<template>
    <div class="navigation-card card-box">
        <h5 class="card-title">
            <!-- <el-icon size="20" color="#1C77C3"><Operation /></el-icon> -->
             <img src="@/assets/img/nav-icon.png" style="margin-right: 10px;" />
            {{ $t('navigation.tit') }}
        </h5>
        <div class="card-text">
            <el-tree
                ref="treeRef"
                :load="loadNode"
                lazy
                :data="treeData"
                :props="treeProps"
                node-key="to"
                icon="ArrowRightBold"
                :expand-on-click-node="false"
                @node-click="handleNodeClick"
                :default-expanded-keys="defaultExpanded"
                :current-node-key="activeExpanded"
                auto-expand-parent
            >
                <template #default="{ node, data }">
                    <span class="custom-tree-node">
                        <el-icon class="node-icon" :size="16" v-if="data.icon">
                            <component :is="data.icon" />
                        </el-icon>
                        <img v-else-if="data.iconImg" :src="data.iconImg" style="display: block; width: 16px" />
                        <span :title="data.labelKey ? t(data.labelKey) : data.label">{{ data.labelKey ? t(data.labelKey) : data.label }}</span>
                    </span>
                </template>
            </el-tree>
            <div class="pagination-box">
                <el-pagination
                    size="small"
                    background
                    v-model:page-size="pagination.limit"
                    v-model:current-page="pagination.page"
                    layout="prev, pager, next, total"
                    :total="pagination.total"
                    class="mt-4"
                    :hide-on-single-page="true"
                    @current-change="getDataList"
                />
            </div>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { reactive, ref, computed } from 'vue'
import { useRouter, useRoute, type RouteLocationNormalized } from 'vue-router'
import type Node from 'element-plus/es/components/tree/src/model/node'

import { useI18n } from 'vue-i18n'
import type { SupportedLocales } from '@/locales/i18n'
import type { MessageSchema } from '@/types/i18n'

import CourseService from '@/api/course'
import UnitService from '@/api/unit'
import UserService from '@/api/user'
import icon1 from '@/assets/img/icon1.svg'
import icon2 from '@/assets/img/icon2.svg'
import icon3 from '@/assets/img/icon3.svg'
import icon4 from '@/assets/img/icon4.png'
interface Tree {
    label?: string // 标题
    labelKey?: string
    to: string // 链接
    identifier: string // 标识符
    isLink?: boolean // 是否是连接
    leaf?: boolean // 是否是叶子结点
    icon?: string // 图标
    children?: Tree[] // 子节点
}

const route = useRoute() as RouteLocationNormalized
const router = useRouter()

const { locale, t } = useI18n<{ message: MessageSchema }, SupportedLocales>()

import type { Pagination } from '@/types/global'
// 分页器
const pagination = ref<Pagination>({
    page: 1,
    limit: 20,
    total: 0,
})
import { useUserStore } from '@/stores/user'
const userStore = useUserStore()
const userInfo = computed(() => userStore.userinfoL)
const loading = ref(false)
const treeRef = ref(null)
// 获取数据列表
function getDataList() {
    loading.value = true
    const searchData = {
        page: pagination.value.page,
        limit: pagination.value.limit,
    }
    CourseService.getUserCourseList(searchData)
        .then(res => {
            const dataList = res.dataList || []
            const courseNodes = dataList.map(item => ({
                label: item.name,
                to: `/console/course/${item.id}`,
                identifier: 'course',
                isLink: true,
                children: [] as Tree[],
            }))
            treeRef.value.updateKeyChildren('myCourse', courseNodes)
            pagination.value = res.pagination || pagination.value
        })
        .finally(() => {
            loading.value = false
        })
}

// 树形控件
const treeProps = {
    label: 'label',
    children: 'children',
    isLeaf: 'leaf',
}
const activeExpanded = route.fullPath
const treeData = reactive<Tree[]>([
    {
        labelKey: 'navigation.menu_1',
        to: '/console',
        identifier: 'home',
        isLink: true,
        children: [
            {
                labelKey: 'navigation.menu_1_1',
                to: '/console/my',
                identifier: 'my',
                leaf: true,
                // icon: 'Grid',
                iconImg: icon4,
                isLink: true,
            },
            {
                labelKey: 'navigation.menu_1_2',
                to: 'site',
                identifier: 'site',
                children: [
                    // {
                    //     labelKey: 'navigation.menu_1_2_1',
                    //     to: '/console/tag/search',
                    //     identifier: 'CollectionTag',
                    //     leaf: true,
                    //     icon: 'Grid',
                    //     isLink: true,
                    // },
                    // {
                    //     labelKey: 'navigation.menu_1_2_2',
                    //     to: '/console/calendar/view',
                    //     identifier: 'calendar',
                    //     leaf: true,
                    //     icon: 'Calendar',
                    //     isLink: true,
                    // },
                    {
                        labelKey: 'navigation.menu_1_2_3',
                        to: '/console/mod/announcement',
                        identifier: 'announcement',
                        leaf: true,
                        iconImg: icon1,
                        isLink: true,
                    },
                    {
                        labelKey: 'navigation.menu_1_2_4',
                        to: '/console/mod/book',
                        identifier: 'book',
                        leaf: true,
                        iconImg: icon2,
                        isLink: true,
                    },
                    {
                        labelKey: 'navigation.menu_1_2_5',
                        to: '/console/mod/contact',
                        identifier: 'contact',
                        leaf: true,
                        iconImg: icon3,
                        isLink: true,
                    },
                ],
            },
            {
                labelKey: 'navigation.menu_1_3',
                to: 'myCourse',
                identifier: 'myCourse',
                children: [],
            },
        ],
    },
])
import { useRoleStore } from '@/stores/role'
const roleStore = useRoleStore()
const defaultExpanded = ref(findNodePath(treeData, route.fullPath).concat(route.fullPath))
console.log(111, defaultExpanded.value)
const loadNode = (node: Node, resolve: (data: Tree[]) => void, reject: () => void) => {
    if (node.level === 0) resolve(treeData)

    // 加载子节点，这里可以根据node.data的信息来决定加载什么
    const nodeData = node.data

    // 处理"我的课程"节点
    if (nodeData.identifier === 'myCourse') {
        const searchData = {
            page: pagination.value.page,
            limit: pagination.value.limit,
        }
        CourseService.getUserCourseList(searchData)
            .then(res => {
                const dataList = res.dataList || []
                pagination.value = res.pagination || pagination.value
                const courseNodes = dataList.map(item => ({
                    label: item.name,
                    to: `/console/course/${item.id}`,
                    identifier: 'course',
                    isLink: true,
                    children: [] as Tree[],
                }))
                resolve(courseNodes)
            })
            .catch(() => {
                resolve([])
            })
    }

    // 处理"课程"节点
    if (nodeData.identifier === 'course') {
        const courseId: number = nodeData.to.split('/').pop()
        UnitService.list(courseId)
            .then(res => {
                const unitNodes: Tree[] = [
                    {
                        labelKey: 'navigation.menu_1_3_1',
                        to: `/console/course/${courseId}/member`,
                        identifier: 'courseMember',
                        isLink: true,
                        children: [] as Tree[],
                    },
                    {
                        labelKey: 'navigation.menu_1_3_2',
                        to: `courseCapacity`,
                        identifier: 'courseCapacity',
                        // isLink: true,
                        icon: 'Finished',
                        leaf: true,
                    },
                    {
                        labelKey: 'navigation.menu_1_3_3',
                        to: `/console/course/${courseId}/grade/user`,
                        identifier: 'gradeUser',
                        isLink: true,
                        icon: 'Files',
                        leaf: true,
                    },
                    {
                        label: '通用',
                        to: `courseGeneral`,
                        identifier: 'courseGeneral',
                        isLink: false,
                        children: [
                            {
                                labelKey: 'router_tit.modForum',
                                to: `/console/course/${courseId}/forum/view?courseId=${courseId}&type=1`,
                                identifier: 'modForum',
                                isLink: true,
                                icon: 'ChatLineSquare',
                                leaf: true,
                            },
                            {
                                labelKey: 'router_tit.modForum2',
                                to: `/console/course/${courseId}/forum?courseId=${courseId}&type=2`,
                                identifier: 'modForum2',
                                isLink: true,
                                icon: 'ChatLineSquare',
                                leaf: true,
                            },
                        ],
                    },
                ]
                res.forEach(unit => {
                    const item = {
                        label: locale.value === 'en' ? unit.title_en : unit.title_cn,
                        to: `/console/course/${courseId}/unit/${unit.id}`,
                        identifier: 'unit',
                        isLink: true,
                        children: [] as Tree[],
                    }
                    unit.resources.map(resources => {
                        let to = ``
                        let icon = ''
                        switch (resources.type) {
                            case 'video':
                                to = `/console/course/${courseId}/unit/${unit.id}/videoTime/${resources.id}`
                                icon = 'VideoPlay'
                                break
                            case 'folder':
                                to = `/console/course/${courseId}/unit/${unit.id}/folder/${resources.id}`
                                icon = 'Folder'
                                break
                            case 'quiz':
                                to = `/console/course/${courseId}/unit/${unit.id}/quiz/${resources.id}`
                                icon = 'ChatLineSquare'
                                break
                            case 'report':
                                to = `/console/course/${courseId}/unit/${unit.id}/assign/${resources.id}`
                                icon = 'Tickets'
                                break

                            default:
                                to = resources.url
                                icon = 'Document'
                                break
                        }
                        item.children.push({
                            label: resources.title,
                            to,
                            icon,
                            identifier: 'resource',
                            isLink: true,
                            leaf: true,
                        })
                    })
                    unitNodes.push(item)
                })
                resolve(unitNodes)
            })
            .catch(() => {
                reject()
            })
    }

    // 处理"课程成员"节点
    if (nodeData.identifier === 'courseMember') {
        const parts = nodeData.to.split('/')
        const courseId = parts[parts.length - 2]
        if (roleStore.isStudent) {
            const memberNodes = [{
                label: `${userInfo.value.last_name} ${userInfo.value.first_name}`,
                to: `/console/user/${userInfo.value.id}?courseId=${courseId}`,
                identifier: 'user',
                isLink: true,
                leaf: true,
            }];
            resolve(memberNodes)
        } else {
            UserService.listToCourse(courseId, {
                page: 1,
                limit: 1000,
            })
                .then(res => {
                    const dataList = res.dataList || []
                    const memberNodes = dataList.map(item => ({
                        label: `${item.last_name} ${item.first_name}`,
                        to: `/console/user/${item.id}?courseId=${courseId}`,
                        identifier: 'user',
                        isLink: true,
                        leaf: true,
                    }))
                    console.log(memberNodes, 111)
                    resolve(memberNodes)
                })
                .catch(() => {
                    reject()
                })
        }
    }

    if (nodeData.children && nodeData.children.length > 0) return resolve(nodeData.children)
}
const handleNodeClick = (data: Tree) => {
    if (data.to.indexOf('http') !== -1) return (window.location.href = data.to)
    if (data.to && data.isLink) return router.push(data.to)
}
function findNodePath(data: Tree[], targetValue: string): string[] {
    // 处理课程路径特殊情况
    if (targetValue.includes('/videoTime/') || targetValue.includes('/folder/') || targetValue.includes('/quiz/') || targetValue.includes('/assign/')) {
        const parts = targetValue.split('/')
        const courseId = parts[3]
        const unitId = parts[5]
        return ['/console', 'myCourse', `/console/course/${courseId}`, `/console/course/${courseId}/unit/${unitId}`]
    }
    if (targetValue.includes('/unit/')) {
        const parts = targetValue.split('/')
        const courseId = parts[3]
        return ['/console', 'myCourse', `/console/course/${courseId}`]
    }
    if (targetValue.includes('/console/course/')) {
        const parts = targetValue.split('/')
        if (parts.length === 4) {
            return ['/console', 'myCourse']
        }
    }

    for (const node of data) {
        // 如果找到目标节点
        if (node.to === targetValue) return ['/console', node.to]

        // 如果有子节点，递归查找
        if (node.children && node.children.length > 0) {
            const result = findNodePath(node.children, targetValue)
            if (result.length > 0) return ['/console', node.to, ...result]
        }
    }

    return ['/console']
}
</script>

<style lang="less" scoped>
.card-box::before {
    background-color: #1c77c3;
}
.pagination-box {
    justify-content: center;
}
:deep(.el-tree) {
    --el-tree-node-hover-bg-color: transparent;
    --el-tree-expand-icon-color: #4c4c4c;
    --el-tree-text-color: #4c4c4c;
    background-color: transparent;

    .el-text {
        color: #4c4c4c;
        font-weight: normal;
    }

    .el-icon.is-leaf {
        padding: 0;
        width: 6px;
    }

    .is-current {
        & > .el-tree-node__content {
            .el-tree-node__label,
            .custom-tree-node {
                color: #000;
                font-weight: bold;
            }
        }
    }

    .custom-tree-node {
        display: flex;
        align-items: center;
        gap: 4px;
        width: calc(100% - 24px);

        span {
            display: block;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }
    }
}

:deep(.el-empty) {
    --el-empty-padding: 0;
    --el-empty-description-margin-top: 0;

    .el-empty__image {
        display: none;
    }
}
</style>
